<?php

namespace app\admin\controller\gashapon;

use app\admin\model\gashapon\Products;
use app\common\controller\Backend;
use app\common\model\Attachment;

/**
 * 期数关联的产品
 *
 * @icon fa fa-circle-o
 */
class GashaponPro extends Backend
{

    /**
     * GashaponPro模型对象
     * @var \app\common\model\GashaponPro
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\GashaponPro;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['gashapon','products'])
                    ->where($where)
                    ->where('gashapon_id',$this->request->param('gid'))
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','status','createtime']);
                $row->visible(['gashapon']);
				$row->getRelation('gashapon')->visible(['title','money']);
				$row->visible(['products']);
				$row->getRelation('products')->visible(['title','pic','rating','thump']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('gid', $this->request->param('ids'));
        return $this->view->fetch();
    }

    /**
     * 单张图片
     * @param $gid
     * @return string|void
     */
    public function add(){
        $gid = $this->request->param('gid');
        if(!$gid){
            $this->error(__('异常'));
        }
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            if(!$params['title']){
                $this->error(__('请输入水印文字/压缩比例/模糊度'));
            }

            //查询附件信息
            $img = $params['pic'];
            $uploads = Attachment::get(['url'=>$img]);
            switch ($params['status'])
            {
                case 1:     //水印
                    $path = ROOT_PATH.'public/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                    $filePath = '/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                    $image = borderWater(ROOT_PATH . 'public' . $img,$params['title'],$path);
                    break;
                case 2:     //压缩
                    $path = ROOT_PATH.'public/uploads/yasuo/'.date('Ymd').'-'.$uploads['filename'];
                    $filePath = '/uploads/mohu/'.date('Ymd').'-'.$uploads['filename'];
                    $image = compressImg(ROOT_PATH . 'public' . $img,$params['title'],$path);
                    break;
                case 3:     //高斯
                    if(in_array($uploads['imagetype'],['png'])) {
                        $sourceImage = imagecreatefrompng(ROOT_PATH . 'public' . $img);

                    }else{
                        $sourceImage = imagecreatefromjpeg(ROOT_PATH . 'public' . $img);

                    }
                    $path = ROOT_PATH.'public/uploads/mohu/'.$uploads['filename'];
                    $filePath = '/uploads/mohu/'.$uploads['filename'];
                    $image = gaussian_blur($sourceImage,$params['title'],$uploads['imagetype'],$path);
                    break;
                default:
                    $this->error(__('请选择处理类型'));
                    break;
            }

            if($image === false){
                $this->error(__('处理异常'));
            }

            //保存图片信息
            $names = explode('.',$uploads['filename']);
            $products =
                Products::create([
                    'title'     => $names[0],
                    'pic'       => $img,
                    'thump'     => $filePath,
                    'rating'    => 'SSR',
                ]);

            \app\common\model\GashaponPro::create([
                'product_id'     => $products['id'],
                'gashapon_id'    => $gid,
            ]);


            $this->success(__('操作成功'));
        }

        return $this->view->fetch();
    }

    /**
     * 单张图片
     * @param $gid
     * @return string|void
     */
    public function edit($ids=null){
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__('No Results were found'));
        }
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            if(!$params['thumptext']){
                $this->error(__('请输入水印文字/压缩比例/模糊度'));
            }

            //查询附件信息
            $img = $params['pic'];
            $uploads = Attachment::get(['url'=>$img]);
            switch ($params['thumptype'])
            {
                case 1:     //水印
                    $path = ROOT_PATH.'public/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                    $filePath = '/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                    $image = borderWater(ROOT_PATH . 'public' . $img,$params['thumptext'],$path);
                    break;
                case 2:     //压缩
                    $path = ROOT_PATH.'public/uploads/yasuo/'.date('Ymd').'-'.$uploads['filename'];
                    $filePath = '/uploads/yasuo/'.date('Ymd').'-'.$uploads['filename'];
                    $image = compressImg(ROOT_PATH . 'public' . $img,$params['thumptext'],$path);
                    break;
                case 3:     //高斯
                    if(in_array($uploads['imagetype'],['png'])) {
                        $sourceImage = imagecreatefrompng(ROOT_PATH . 'public' . $img);

                    }else{
                        $sourceImage = imagecreatefromjpeg(ROOT_PATH . 'public' . $img);

                    }
                    $path = ROOT_PATH.'public/uploads/mohu/'.$uploads['filename'];
                    $filePath = '/uploads/mohu/'.$uploads['filename'];
                    $image = gaussian_blur($sourceImage,$params['thumptext'],$uploads['imagetype'],$path);
                    break;
                default:
                    $this->error(__('请选择处理类型'));
                    break;
            }

            if($image === false){
                $this->error(__('处理异常'));
            }

            //保存图片信息
            $names = explode('.',$uploads['filename']);
            $products =
                Products::where('id',$row['product_id'])->update([
                    'title'     => $names[0],
                    'pic'       => $img,
                    'thump'     => $filePath,
                    'rating'    => 'SSR',
                    'thumptype' => $params['thumptype'],
                    'thumptext' => $params['thumptext'],
                ]);

            $this->success(__('操作成功'));
        }
        $product = \app\common\model\GashaponProducts::get($row['product_id'])->toArray();
        if($product){
            unset($product['id']);
            $row = array_merge($row->toArray(),$product);
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 图片批量处理
     * @param $gid
     * @return string
     * @throws \think\Exception
     */
    public function adds($gid){

        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            if(!$params['title']){
                $this->error(__('请输入水印文字/压缩比例/模糊度'));
            }
            $imageArr = explode(',',$params['pic']);
            foreach ($imageArr as $img)
            {
                //查询附件信息
                $uploads = Attachment::get(['url'=>$img]);
                switch ($params['status'])
                {
                    case 1:     //水印
                        $path = ROOT_PATH.'public/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                        $filePath = '/uploads/water/'.date('Ymd').'-'.$uploads['filename'];
                        $image = borderWater(ROOT_PATH . 'public' . $img,$params['title'],$path);
                        break;
                    case 2:     //压缩
                        $path = ROOT_PATH.'public/uploads/yasuo/'.date('Ymd').'-'.$uploads['filename'];
                        $filePath = '/uploads/mohu/'.date('Ymd').'-'.$uploads['filename'];
                        $image = compressImg(ROOT_PATH . 'public' . $img,$params['title'],$path);
                        break;
                    case 3:     //高斯
                        if(in_array($uploads['imagetype'],['png'])) {
                            $sourceImage = imagecreatefrompng(ROOT_PATH . 'public' . $img);

                        }else{
                            $sourceImage = imagecreatefromjpeg(ROOT_PATH . 'public' . $img);

                        }
                        $path = ROOT_PATH.'public/uploads/mohu/'.$uploads['filename'];
                        $filePath = '/uploads/mohu/'.$uploads['filename'];
                        $image = gaussian_blur($sourceImage,$params['title'],$uploads['imagetype'],$path);
                        break;
                    default:
                        $this->error(__('请选择处理类型'));
                        break;
                }

                if($image === false){
                    $this->error(__('处理异常'));
                }

                //保存图片信息
                $names = explode('.',$uploads['filename']);
                $products =
                    Products::create([
                        'title'     => $names[0],
                        'pic'       => $img,
                        'thump'     => $filePath,
                        'thumptext'     => $params['title'],
                        'thumptype'     => $params['status'],
                        'rating'    => 'SSR',
                    ]);

                \app\common\model\GashaponPro::create([
                    'product_id'     => $products['id'],
                    'gashapon_id'    => $gid,
                ]);
            }

            $this->success(__('操作成功'));
        }

        return $this->view->fetch();
    }

}

/**
 * 模糊处理
 * @param $image
 * @param $blurFactor
 * @param $type
 * @param $path
 * @return mixed
 */
function gaussian_blur($image, $blurFactor , $type ,$path) {
    // 应用模糊效果
    for ($i = 0; $i < $blurFactor; $i++) {
        imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR);
    }

    // 保存模糊处理后的图片
    $outputPath =$path;
    if($type == 'png'){
        imagepng($image, $outputPath);
    }else{
        imagejpeg($image, $outputPath);
    }

    // 释放内存
    imagedestroy($image);
    return $outputPath;
}

/**
 * 图片压缩
 * @param $imagePath
 * @param $quality
 * @return string
 */
function compressImg($imagePath,$quality,$path){

    // 获取图片信息
    $imageInfo = getimagesize($imagePath);
    $mime = $imageInfo['mime'];

    // 加载图片
    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($imagePath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($imagePath);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($imagePath);
            break;
        default:
            return false;
            break;
    }

    if (!$image) {
        return false;
    }

    // 获取原始宽度和高度
    list($width, $height) = getimagesize($imagePath);

    // 创建一个新的空白图片
    $newWidth = round($width * round($quality / 100,3));
    $newHeight = round($height * round($quality / 100,3));


    $newImage = imagecreatetruecolor($newWidth, $newHeight);

    // 将原始图片复制到新图片并调整大小
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    switch ($mime) {

        case 'image/png':
            imagepng($newImage, $path, $quality);
            break;
        case 'image/gif':
            imagegif($newImage, $path, $quality);
            break;
        default:
            imagejpeg($newImage, $path, $quality);
            break;
    }

    // 释放内存
    imagedestroy($image);
    imagedestroy($newImage);

    return $path;
}

/**
 * 水印
 */
function borderWater($imagePath,$text,$path,$color=[255, 255, 255],$fontSize=20){

    // 获取图片信息
    $imageInfo = getimagesize($imagePath);
    $mime = $imageInfo['mime'];

    // 加载图片
    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($imagePath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($imagePath);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($imagePath);
            break;
        default:
           return  false;
           break;
    }

    // 设置文字颜色
    $textColor = imagecolorallocate($image, $color[0], $color[1], $color[2]);

    // 获取原始图片的宽度和高度
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);

    // 使用 TrueType 字体
    $fontFile = ROOT_PATH.'public/uploads/StdNW8.otf'; // 替换为实际的字体文件路径

    // 计算文字位置
    $textBox = imagettfbbox($fontSize, 0, $fontFile, $text);
    $textWidth = $textBox[2] - $textBox[0];
    $textHeight = $textBox[1] - $textBox[7];

    // 添加上下的水印（横着）
    $x = ($imageWidth - $textWidth) / 2;
    imagettftext($image, $fontSize, 0, $x, $textHeight + 10, $textColor, $fontFile, $text); // 上
    imagettftext($image, $fontSize, 0, $x, $imageHeight - 10, $textColor, $fontFile, $text); // 下

    // 添加左右的水印（竖着）
    $y = ($imageHeight - $textWidth) / 2 + $textWidth;
    imagettftext($image, $fontSize, 90, $textHeight + 10, $y, $textColor, $fontFile, $text); // 左
    imagettftext($image, $fontSize, 90, $imageWidth - 10, $y, $textColor, $fontFile, $text); // 右

    // 添加中间的水印（横着）
    $x = ($imageWidth - $textWidth) / 2;
    $y = ($imageHeight + $textHeight) / 2;
    imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $text); // 中

    switch ($mime) {

        case 'image/png':
            imagepng($image, $path);
            break;
        case 'image/gif':
            imagegif($image, $path);
            break;
        default:
            imagejpeg($image, $path);
            break;
    }
    // 释放内存
    imagedestroy($image);

    return $path;
}